import {
  getEnsureList,
  placeOrder,
  getPreOrder,
} from '../../../api/index';


Page({
  data: {
    baseUrl: 'https://oss.peibanmao.com/',
    imgUrl: '',
    favor: true,
    ensureList: [],
    unitPrice: null,
    enSuerId: null,
    // buyNum:1,
    // payLevelId:1,
    titleId: null,
    address: '',
    phoneNum: null,
    orderId: null,
  },
  onShow() {
    this.getTabBar()
  },

  onLoad(options) {
    this.init();
    console.log(options.id, 'opop')
    this.setData({
      titleId: options.id
    })
  },

  init() {
    this.getEnsureListFn()
  },
  async getEnsureListFn() {
    const res = await getEnsureList()
    let item = res.data.item || []
    console.log(this.data.titleId, 'this.data.titleId')
    let filteredItem = item.filter(item => item.id == this.data.titleId);

    item = filteredItem.map(i => {
      return {
        ...i,
        active: false
      }
    })
    item[0].active = true //默认第1项选中
    this.setData({
      ensureList: item,
      unitPrice: item[0].price,
      enSuerId: item[0].id,
      address: item[0].address,
      phoneNum: item[0].phoneNum,
      imgUrl: item[0].imgUrl
    })
  },
  onChang(e) {
    const item = e.currentTarget.dataset.item
    // const idx = e.currentTarget.dataset.index
    this.data.ensureList.forEach(i => {
      if (i.id == item.id) {
        i.active = true
      } else {
        i.active = false
      }
    })
    item.active = true
    console.log(this.data.ensureList, 'this.data.ensureList')
    this.setData({
      enSuerId: item.id,
      unitPrice: item.price,
      ensureList: this.data.ensureList
    })



  },
  goToPay() {
    if (wx.getStorageSync('user_token')) {
      this.placeOrderFn()
    } else {
      wx.showToast({
        title: '请先登录',
        icon: 'error',
        duration: 1500
      })
      setTimeout(function () {
        wx.switchTab({
          url: '/pages/usercenter/index'
        });
      }, 1500);
    }
  },
  async placeOrderFn() {
    console.log(this.data, 'this.data.enSuerId')
    try {
      const res = await placeOrder({
        ensureId: this.data.enSuerId, //套餐id
        unitPrice: this.data.unitPrice, //单价
        buyNum: 1, //购买份数 默认为1
        payLevelId: 1 // 支付通道id 默认为1
      })
      if (res.code == 500) {
        wx.showToast({
          title: res.msg,
          icon: 'error',
        })
        return
      } else {
        console.log('quxiaoquxiao')
        this.setData({
          orderId: res.data.orderId
        })
      }
      getPreOrder({
        orderSn: res.data.orderSn
      }).then(res => {

        delete res?.data.appId
        const obj = {
          ...res?.data
        }
        wx.requestPayment({
          ...obj,
          totalFee: 1,
          success: (res) => {
            // 支付成功后的回调函数  跳待使用详情页
            console.log('支付成功', res);
            const id = this.data.orderId
            const status = 10
            // 更新订单状态等操作  
            wx.navigateTo({
              url: '/pages/order/order-detail/index?status=' + status + '&id=' + id,
            })
          },
          fail: (res) => {
            // 支付失败后的回调函数  跳待支付详情页
            console.log('支付失败', this.data, this.data.orderId, );
            // 处理支付失败的情况  
            const id = this.data.orderId
            const status = 5
            wx.navigateTo({
              url: '/pages/order/order-detail/index?status=' + status + '&id=' + id,
            })
          }
        });
      })
    } catch (error) {
      console.log('111', error)
      if (error == '您有未支付订单') {
        wx.showToast({
          title: error,
          icon: 'error',
          duration: 1000
        })
        setTimeout(() => {
          //跳待支付页面
          wx.navigateTo({
            url: '/pages/order/order-list/index?status=5',
          })
        }, 1000)
      }
    }
  },
  onFavor() {
    this.setData({
      favor: !this.data.favor,
    });
  },
  handleContact(e) {
    console.log(e.detail.path, 'e.detail.path')
    console.log(e.detail.query)
  },
});